<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;
use think\facade\Cache;
use think\facade\Event;

class User extends Base
{

    protected $name = 'user';

    protected $type = [
        'active_time' => 'timestamp',
    ];

    protected function level()
    {
        return $this->hasOne(Level::class, 'id', 'level_id');
    }
    
    protected function team()
    {
        return $this->hasOne(TeamLevel::class, 'id', 'team_id');
    }
    
    public function assets()
    {
        return $this->hasOne(Assets::class, 'uid');
    }

    public function getNicknameAttr($value)
    {
        return $value ?: Cache::get('system')['default_nickname'];
    }

    public function getPhotoAttr($value)
    {
        return $value ?: Cache::get('system')['default_photo'];
    }

    protected function getMinTeamAttr($value, $data)
    {
        return self::geMinTeam($data['id']);
    }

    public static function _save($param, $logs)
    {
        parent::startTrans();
        try {
            if (isset($param['id']) && $param['id']) {
                $original = self::where($logs['pk'], $param[$logs['pk']])->find();
                if (empty($original)) {
                    return ['code' => -1, 'msg' => '记录不存在，请检查！'];
                }
                $logs['original'] = $original;
                $model = self::update($param);
                $logs['operation'] = 'save';
                if ($logs['writeLog']) {
                    $logs['model'] = $model;
                    Event::trigger('Logs', $logs);
                }
            } else {
                $code = generate(6, '', 1);
                $count = parent::where(['code' => $code])->count();
                if ($count) {
                    return ['code' => -1, 'msg' => '会员编号已被注册'];
                }
                $count = parent::where(['mobile' => $param['mobile']])->count();
                if ($count) {
                    return ['code' => -1, 'msg' => '手机号已被注册'];
                }
                if(empty($param['parent_code'])){
                    return ['code' => -1, 'msg' => '请填写推荐人编号'];
                }
                $parent = parent::where(['code' => $param['parent_code'], 'is_active' => 2])->find();
                if (empty($parent)) {
                    return ['code' => -1, 'msg' => '推荐人不存在或未激活'];
                }
                $param['code'] = $code;
                $param['mobile'] = trim($param['mobile']);
                $param['parent_id'] = $parent->id;
                $param['parent_name'] = $parent->nickname;
                $param['password'] = !empty($param['password']) ? md5($param['password']) : md5('111111');
                $param['pay_password'] = !empty($param['pay_password']) ? md5($param['pay_password']) : md5('222222');
                parent::create($param);
                Event::trigger('Statistics', ['key' => 'user', 'value' => 1]);
            }
            parent::commit();
            return ['code' => 1, 'msg' => '操作成功', 'url' => url('login/index')->build()];

        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function onAfterInsert($user)
    {
        if ($user->parent_code) {
            Relation::generate($user->id, $user->code, $user->parent_id, $user->parent_code);
        }
        $user->assets()->save(['uid' => $user->id]);
    }


    public static function recharge($param, $admin)
    {
        parent::startTrans();
        try {
            $user = parent::find($param['id']);
            if ($user->isEmpty()) {
                return json(['code' => -1, 'msg' => '未查询到相关会员']);
            }
            $account = get_pay_way($param['account']);
            if ($param['mode'] == 1) {
                Target::Account()
                    ->basics($param['id'], $param['account'], $param['amount'], '后台充值', '+')
                    ->setMsg($param['remarks'])
                    ->createRecharge();
                $logs = '后台充值【' . $account . '】金额【' . $param['amount'] . '】会员【' . $user->code . '】';
            } else {
                Target::Account()
                    ->basics($param['id'], $param['account'], $param['amount'], '后台扣除', '-')
                    ->setMsg($param['remarks'])
                    ->createRecharge();
                $logs = '后台扣除【' . $account . '】金额【' . $param['amount'] . '】会员【' . $user->code . '】';
            }

            Logs::adds($logs, $admin['id'], $admin['admin_name']);

            parent::commit();
            return json(['code' => 1, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            parent::rollback();
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }


    /**
     * 检测用户收款方式
     * @param $user
     */
    public static function checkReceipt($user)
    {
        // 微信
        if (empty($user->wechat_name) && empty($user->wechat_image)
            && empty($user->alipay_name) && empty($user->alipay_image)
            && empty($user->bank_name) && empty($user->bank_number)) {
            return false;
        }
        return true;
    }

    /**
     * @param $uid
     * @return float|int
     * 原点 2021年12月28日11:50:17 计算小区业绩
     */
    public static function geMinTeam($uid)
    {
        $areaData = parent::where('parent_id', $uid)->order('team_total', 'desc')->column('my_total+team_total as team_total');
        if ($areaData) {
            array_shift($areaData);
            if (!empty($areaData)) return array_sum($areaData);
        }
        return 0;
    }
    

    public static function security($param, $user, $first = false): array
    {
        try {
            $pass = $param['type'];
            $msg = '已设置';
            if (!$first) {
                if (md5($param['old_password']) != $user->$pass) {
                    return ['code' => -1, 'msg' => '旧密码错误'];
                }
                if (md5($param['old_password']) == md5($param['password'])) {
                    return ['code' => -1, 'msg' => '新旧密码相同'];
                }
                $msg = '已修改';

            }

            $user->$pass = md5($param['password']);
            if ($pass == 'password') {
                $user->token = md5(time() . json_encode($user));
                cookie('token', null);
            }
            $user->save();

            return ['code' => 1, 'msg' => $msg];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 取消商家
     */
    public static function cancelMerchant($param){
        try {   
            $merchant = Merchant::where(['uid'=>$param['id']])->find();
            $merchant->status=3;
            $merchant->reject_msg='商家身份已被取消！需重新申请商家入驻！';
            $merchant->save();
            Product::where('merchant_id',$merchant->id)->update(['status'=>0,'is_audit'=>1]);
            parent::where('id',$param['id'])->update(['is_merchant'=>0]);
            return ['code' => 1, 'msg' => '取消商家成功！'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

}
